package sfeir.gwt.ergosoom.server;

import org.restlet.engine.util.DigestUtils;

import sfeir.gwt.ergosoom.client.ClientApi;
import sfeir.gwt.ergosoom.client.model.Profile;
import sfeir.gwt.ergosoom.server.service.ProfileService;
import sfeir.gwt.ergosoom.server.service.ProfileServiceImpl;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Singleton;

@SuppressWarnings("serial")
@Singleton
public class ClientApiServiceImpl extends RemoteServiceServlet implements ClientApi {

    private ProfileService getProfileService() {
        return new ProfileServiceImpl();
    }

    @Override
    public Long createProfile(Profile profile) throws NotLoggedInException {
        if (profile.getPassword() != null && !profile.getPassword().isEmpty()) {
            profile.setPassword(DigestUtils.toMd5(profile.getPassword()));
        }
        getProfileService().saveProfile(profile);
        return 0L;
    }

    @Override
    public Profile getProfile(String email) throws NotLoggedInException {
        return getProfileService().getProfile(email);
    }

    @Override
    public Boolean checkAlias(String alias) throws NotLoggedInException {
        return getProfileService().checkAlias(alias);
    }

    @Override
    public Profile login(String login, String password, Boolean encodePass) throws NotLoggedInException {
        if (encodePass)
            password = DigestUtils.toMd5(password);
        Profile p = getProfileService().login(login, password);
        if (p != null) {
            getThreadLocalRequest().getSession(true).setAttribute("ergosoom.login", p.getEmail());
            getThreadLocalRequest().getSession().setAttribute("ergosoom.pass", password);
            return p;
        }
        else
            throw new NotLoggedInException();
    }

    @Override
    public Profile signup(Profile profile) throws NotLoggedInException {
        profile.setPassword(DigestUtils.toMd5((profile.getPassword())));
        getProfileService().saveProfile(profile);
        return profile;
    }

//    public static String md5(String key) {
//        byte[] uniqueKey = key.getBytes();
//        byte[] hash = null;
//        try {
//            hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
//        }
//        catch (NoSuchAlgorithmException e) {
//            throw new Error("no MD5 support in this VM");
//        }
//        StringBuffer hashString = new StringBuffer();
//        for (int i = 0; i < hash.length; ++i) {
//            String hex = Integer.toHexString(hash[i]);
//            if (hex.length() == 1) {
//                hashString.append('0');
//                hashString.append(hex.charAt(hex.length() - 1));
//            }
//            else {
//                hashString.append(hex.substring(hex.length() - 2));
//            }
//        }
//        return hashString.toString();
//    }
}
